package com.saasexpert.app.kauphy.dao;


import com.saasexpert.app.kauphy.model.CatalogEntry;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.Collection;

@Transactional
public class CatalogEntryDaoImpl<T extends CatalogEntry>
        implements CatalogEntryDao<T> {

    public CatalogEntryDaoImpl(T entity) {
        this.entity = entity;
    }

    @PersistenceContext (unitName ="wordpress-basic")
    protected EntityManager entityManager;

    T entity ;

    public void setEntity(T obj) {
            entity = obj ;
    }

    protected  String getEntityName() {
        return entity.getClass().getSimpleName();
    }

    @Transactional(readOnly = true)
    public T findById(long id) {
        return (T) entityManager.find(entity.getClass(), new Long(id));
    }

    @Transactional(readOnly = true)
    @SuppressWarnings("unchecked")
    public Collection<T> findByName(String name) {
        Query q = entityManager.createQuery("select r from " +
                getEntityName() + " r where r.name = :name");
        q.setParameter("name", name);
        return q.getResultList();
    }

    public T save(T entity) {
        T  merged = entityManager.merge(entity);
        entityManager.flush();
        entity.setId(merged.getId());
        return entity ;
    }

    public void delete(T entity) {
        entityManager.remove(entity);
    }

}
